import React, { FC, useEffect } from 'react';
import { Button, Form, Input, Space, App, Select } from 'antd';
import { FormConfig } from './config';
import CommonRadio from '@/common/CommonRadio';
import dayjs from 'dayjs';
import './style.less';
import request from '@/config/request';
import { dataProps } from './data';

const Components: { [name: string]: React.ElementType } = {
  Input,
  Radio: CommonRadio,
  Select,
};

interface IProps {
  onCancel: Function;
  setIsRefresh: Function;
  record: boolean | dataProps;
}

const Create: FC<IProps> = ({ onCancel, setIsRefresh, record }) => {
  const { message } = App.useApp();
  const [form] = Form.useForm();

  useEffect(() => {
    if (typeof record === 'object') {
      form.setFieldsValue(record);
    }
  }, [record]);

  const onFinish = (values: any) => {
    const url = typeof record === 'object' ? '/updateEduMessage' : '/addEduMessage';
    const obj = { ...values };
    obj.create_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
    if (typeof record === 'object') {
      obj.id = record.id;
    }
    request.post(url, obj).then((ret: any) => {
      if (ret.code === 0) {
        message.success(ret.msg);
        setIsRefresh({});
      }
      onCancel();
    });
  };
  return (
    <Form name="create" form={form} layout="vertical" onFinish={onFinish}>
      {FormConfig.map((item) => {
        const Component = item.component ? Components[item.component] : null;
        return (
          <Form.Item name={item.name} label={item.label} key={item.id} rules={item.rules} {...item.props}>
            {Component && <Component {...item.componentProps} placeholder={item.placeholder} />}
          </Form.Item>
        );
      })}
      <Form.Item className="form-item-submit">
        <Space>
          <Button onClick={() => onCancel()}>取消</Button>
          <Button type="primary" htmlType="submit">
            完成
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default Create;
